<template>
    <div class="editor-panpel" :style="size">

        <!-- 操作区域 -->
        <div class="editor-zoom" :style="zoomStyle">
            <!-- 渲染区 -->
            <DesignerEditorRender :zoom="zoom" :gridline="gridline" ref="render" />

            <!-- 网格 -->
            <DesignerEditorGridline v-if="!activePiece || activePiece.layers.length == 0" />

            <!-- 选中操作区 -->
            <!-- <DesignerEditorOperate :zoom="zoom" /> -->
            <DesignerEditorOperate v-show="!operateHide" :zoom="zoom" :activeSurface="activeSurface"
                                   :activePiece="activePiece" :activeLayer="activeLayer" :activeDst="activeDst"
                                   @selectLayer="selectLayer($event)" @updateLayer="updateLayer($event)"
                                   @updateDst="updateDst($event)" />
        </div>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import DesignUtils from "@/utils/DesignUtils.js";
export default {
    props: {
        gridline: { type: Boolean, default: false },
        zoom: { type: Boolean, default: false },
    },
    data () {
        return {
            mouse: null,
            masks: [],
            size: null
        };
    },
    computed: {
        ...mapGetters("designer", {
            pieces: "getPieces",
            necklabelInfo: 'getNecklabelInfo',
            activeSurface: "getActiveSurface",
            activePiece: "getActivePiece",
            activeLayer: 'getActiveLayer',
            lastActiveLayer: 'getLastActiveLayer',
            activeDst: 'getActiveDst',
            layers: "getActivePieceLayers",
        }),
        // 是否是领标
        operateHide () {
            const activePiece = this.activePiece || { canvas_name: '' }
            const isNecklabel = activePiece.canvas_name == 'Neck Label Inner';
            return isNecklabel && this.necklabelInfo.active;
        },

        // 缩放
        zoomStyle () {
            if (!this.zoom || !this.activePiece) {
                return null;
            } else if (this.activePiece.type == 2 && (this.activeLayer || this.lastActiveLayer)) {
                // 刺绣的放大
                const piece = this.activePiece;
                const layer = this.activeLayer || this.lastActiveLayer;
                const size = DesignUtils.rectRealSize(
                    layer.w,
                    layer.h,
                    piece.canvas_rotate + layer.rotate
                );
                const scale = Math.max(
                    size.width / piece.outer_width,
                    size.height / piece.outer_height
                );

                const center = DesignUtils.coordinateRotation(layer.x + 0.5 * layer.w - 0.5, layer.y + 0.5 * layer.h, 0.5 * piece.canvas_width, 0.5 * piece.canvas_height, piece.canvas_rotate)
                const left = (piece.canvas_left + center.x - 0.5 * layer.w) / piece.outer_width;
                const top = (piece.canvas_top + center.y - 0.5 * layer.h) / piece.outer_height;
                const offsetX = scale - layer.w / piece.outer_width;
                const offsetY = scale - layer.h / piece.outer_height;

                return {
                    width: 100 / scale + "%",
                    height: 100 / scale + "%",
                    left: (-100 * (left - 0.5 * offsetX)) / scale + "%",
                    top: (-100 * (top - 0.5 * offsetY)) / scale + "%",
                };

            } else {
                const piece = this.activePiece;
                const size = DesignUtils.rectRealSize(
                    piece.canvas_width,
                    piece.canvas_height,
                    piece.canvas_rotate
                );
                const scale = Math.max(
                    size.width / piece.outer_width,
                    size.height / piece.outer_height
                );

                const left = piece.canvas_left / piece.outer_width;
                const top = piece.canvas_top / piece.outer_height;
                const offsetX = scale - piece.canvas_width / piece.outer_width;
                const offsetY = scale - piece.canvas_height / piece.outer_height;

                return {
                    width: 100 / scale + "%",
                    height: 100 / scale + "%",
                    left: (-100 * (left - 0.5 * offsetX)) / scale + "%",
                    top: (-100 * (top - 0.5 * offsetY)) / scale + "%",
                };
            }
        },

        // 遮罩加载之后
        maskLoaded () {
            if (!this.activePiece) {
                return "";
            } else {
                let url = this.activePiece.mask_image;
                let active = this.masks.filter((item) => item.url == url)[0];
                return active && active.loaded;
            }
        },
    },

    methods: {

        // 选中图层
        selectLayer (layer) {
            if (!layer) {
                this.$store.commit("designer/SET_ACTIVE_LAYER", null);
            } else if (this.activePiece.layers.indexOf(layer) >= 0) {
                this.$store.commit("designer/SET_ACTIVE_LAYER", layer);
            } else {
                const piece = this.pieces.filter(i => i.layers.indexOf(layer) >= 0)[0];
                const index = piece.layers.indexOf(layer);

                if (piece) {
                    // 这里有个奇怪的问题，SET_ACTIVE_LAYER获取的排序为1
                    this.$store.commit("designer/SET_ACTIVE_PIECE", piece);
                    this.$store.commit("designer/SET_ACTIVE_LAYER_INDEX", index);
                }
            }
        },



        updateLayer (change) {
            this.$store.commit('designer/SET_LAYER_VALUE', change);
        },

        updateDst (change) {
            this.$store.commit('designer/SET_DST_VALUE', change);
        },


        // 删除图层
        removeLayer (layer) {
            // 删除当前图层，默认选中下一个图层
            let index = this.layers.indexOf(layer);
            let active = Math.min(this.layers.length, index + 1) - 1;
            this.$store.dispatch("designer/delLayer", this.layers[active]);

            // 刺绣逻辑,当删除最后一个图层并且时当前面还有其他绣框时优先选择其他绣框
            if (layer.type === 'emb' && index == 0 && this.activePiece.layers) {
                const first_layer = this.activePiece.layers[0];
                this.$store.commit("designer/SET_ACTIVE_LAYER", first_layer);
                this.$emit('global:DESIGN_NOTIFY_CHECK')
                this.$emit('global:DESIGN_NOTIFY_LIMIT')
            }
            // this.$store.dispatch("designer/delLayer",layer);
        },

        removeDst (option) {
            const layer = option.layer;
            const dst = option.dst;
            const index = layer && layer.dists ? layer.dists.indexOf(dst) : -1;

            if (index < 0) {
                // 不管
            } else if (layer && layer.dists && layer.dists.length == 1) {
                // 只有一个图层，把整个台板给删除
                // layer.dists = []
                this.removeLayer(layer)
                this.$store.commit("designer/SET_ACTIVE_DST_INDEX", -1);
                this.$emit('global:DESIGN_NOTIFY_CHECK')
                this.$emit('global:DESIGN_NOTIFY_LIMIT')
            } else {
                // 只删除dst
                layer.dists = layer.dists.filter(i => i != dst)
                this.$store.commit("designer/SET_ACTIVE_DST_INDEX", -1);
                this.$store.commit("designer/SET_ACTIVE_LAYER_PRICE", this.activeLayer);
                this.$emit('global:DESIGN_NOTIFY_CHECK')
                this.$emit('global:DESIGN_NOTIFY_LIMIT')
            }
        },


        // 获取有效的id值
        getUsableId () {
            var id = 1;
            var ids = this.layers.map(function (i) {
                return i.id;
            });
            var res = [];
            var next = true;
            var count = 1;

            while (next) {
                ids.indexOf(id) < 0 && res.push(id);
                id = id + 1;
                next = res.length < count;
            }
            return res[0];
        },

        // 插入文字
        insertText () {
            if (this.activePiece) {
                let layers = this.activePiece.layers;
                let piece = this.activePiece;
                // 当前视口24像素大小
                let text = {
                    id: this.getUsableId(),
                    type: "text", // 类型[image|text]
                    text: "Text", // 文字内容
                };

                // 根据font_size来计算宽高、位置
                // this.layers.push(text);
                DesignUtils.resetText(text, piece);
                this.$store.commit("designer/ADD_LAYER", text);
                this.$store.commit(
                    "designer/SET_ACTIVE_LAYER",
                    layers.slice(-1)[0]
                );
            }
        },

        // 插入图片
        insertImage (option) {
            if (this.activePiece) {
                let layers = this.activePiece.layers;
                let image = {
                    id: this.getUsableId(),
                    type: "image", // 类型[image|text]
                    url: option.url,
                    name: option.name,
                    imageW: option.width, // 图片宽度
                    imageH: option.height, // 图片高度
                };

                // image.url = 'https://pod-product.oss-accelerate.aliyuncs.com/female.png';
                // image.imageW = 4800;
                // image.imageH = 6400;

                DesignUtils.resetImage(image, this.activePiece);
                this.$store.commit("designer/ADD_LAYER", image);
                this.$store.commit(
                    "designer/SET_ACTIVE_LAYER",
                    layers.slice(-1)[0]
                );
            }
        },

        // 插入图片
        copyLayer (layer) {
            if (this.activePiece) {
                let piece = this.activePiece;
                let option = {
                    index: piece.layers.indexOf(layer) + 1,
                    layer: JSON.parse(JSON.stringify(layer)),
                };

                option.layer.id = this.getUsableId();
                this.$store.commit("designer/PUT_LAYER", option);
                this.$store.commit("designer/SET_ACTIVE_LAYER", option.layer);
            }
        },

        copyDst (option) {
            if (this.activePiece) {
                let dst = {
                    ...option.dst,
                    id: DesignUtils.getUsableId({ layers: option.layer.dists }),
                }

                option.layer.dists.push(dst);
                this.$store.commit("designer/SET_ACTIVE_LAYER_INDEX", this.activePiece.layers.indexOf(option.layer));
                this.$store.commit("designer/SET_ACTIVE_DST_INDEX", option.layer.dists.indexOf(dst));
                this.$store.commit("designer/SET_ACTIVE_LAYER_PRICE", option.layer);
                this.$emit('global:DESIGN_NOTIFY_CHECK')
                this.$emit('global:DESIGN_NOTIFY_LIMIT')

            }
        },

        resize () {
            const rect = this.$el.parentNode.getBoundingClientRect();
            const min = Math.min(rect.width, rect.height);
            this.size = { width: 100 * min / rect.width + '%', height: 100 * min / rect.height + '%' }

            this.$refs.render && this.$refs.render.resize && this.$refs.render.resize()
        }
    },

    created () {
        this.$on("global:DESIGN_INSERT_TEXT", this.insertText);
        this.$on("global:DESIGN_INSERT_IMAGE", this.insertImage);
        this.$on("global:DESIGN_REMOVE_LAYER", this.removeLayer);
        this.$on("global:DESIGN_REMOVE_DST", this.removeDst);
        this.$on("global:DESIGN_COPY_LAYER", this.copyLayer);
        this.$on("global:DESIGN_COPY_DST", this.copyDst);

        this.$on("global:DESIGN_RESET_LAYER", (option) => {
            let layer = option.layer;
            let piece = option.piece;

            if (!option.piece || !option.layer) {
                return;
            } else if (layer.type == "text") {
                option.layer.font_size = 100;
                DesignUtils.resetText(option.layer, option.piece);
                this.$store.commit("designer/SET_LAYER_VALUE", option.layer);
            } else if (layer.type == "image") {
                DesignUtils.resetImage(option.layer, option.piece);
                this.$store.commit("designer/SET_LAYER_VALUE", option.layer);
            }
        });
    },
    mounted () {
        this.resize();
        window.addEventListener('resize', this.resize, false);
    },
    beforeDestroy () {
        window.removeEventListener('resize', this.init, false);
    }
};
</script>

<style lang="scss" scoped>
.editor-panpel {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    height: 100%;
    text-align: center;

    &>img {
        height: 100%;
    }

    .editor-zoom {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
    }
}
</style>
